package com.scuec.groupfive.service.impl;

import com.scuec.groupfive.entity.SysLog;
import com.scuec.groupfive.entity.UserInfo;
import com.scuec.groupfive.mapper.SysLogMapper;
import com.scuec.groupfive.service.LogService;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class LogServiceImpl implements LogService {

    private final SysLogMapper sysLogMapper;

    public LogServiceImpl(SysLogMapper sysLogMapper) {
        this.sysLogMapper = sysLogMapper;
    }

    @Override
    public void recordLoginLog(UserInfo user, HttpServletRequest request) {
        SysLog log = buildBaseLog(user.getUserId(), "用户登录", request);
        log.setRemark(user.getUsername() + "登录系统");
        sysLogMapper.insertLog(log);
    }

    @Override
    public void recordOperationLog(Integer userId, String operation, HttpServletRequest request) {
        SysLog log = buildBaseLog(userId, operation, request);
        log.setRemark("用户操作记录");
        sysLogMapper.insertLog(log);
    }

    // 新增方法实现
    @Override
    public List<Map<String, Object>> countUserLogins(Date startDate, Date endDate) {
        return sysLogMapper.countUserLogins(startDate, endDate);
    }

    // 构建基础日志对象（私有方法）
    private SysLog buildBaseLog(Integer userId, String content, HttpServletRequest request) {
        SysLog log = new SysLog();
        log.setUserID(userId);
        log.setLogContent(content);
        log.setIpAddress(getClientIP(request));
        log.setOs(getUserOS(request));
        log.setIe(getUserBrowser(request));
        log.setCreateDate(new Date());
        return log;
    }

    // 获取客户端IP
    private String getClientIP(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    // 简化版获取用户操作系统
    private String getUserOS(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent == null) return "Unknown";

        userAgent = userAgent.toLowerCase();
        if (userAgent.contains("windows")) return "Windows";
        if (userAgent.contains("mac")) return "Mac OS";
        if (userAgent.contains("linux")) return "Linux";
        return "Other OS";
    }

    // 简化版获取用户浏览器
    private String getUserBrowser(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent == null) return "Unknown";

        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) return "IE";
        if (userAgent.contains("Firefox")) return "Firefox";
        if (userAgent.contains("Chrome")) return "Chrome";
        if (userAgent.contains("Safari")) return "Safari";
        return "Other Browser";
    }
}